<template>
    <!-- @contextmenu.prevent.stop="contextMenuClick(baseFolder, $event)" -->
    <div class="side-wrap">
        <div class="title" :class="{ callapse: appStore.menuCollapse }">
            <span v-if="appStore.menuCollapse">XKL</span>
            <span v-else class="ml-10 title-text">xkl_admin</span>
        </div>
        <div class="side-scroll">
            <el-menu :default-active="appStore.defaultActive" :collapse="appStore.menuCollapse"
                class="el-menu-vertical-demo" active-text-color="#fff" background-color="#25282c" text-color="#aaa"
                :router="true">
                <el-menu-item index="/home">
                    <div class="mr-2 align-item-center">
                        <icon-svg class="mr-2" name="dot" />
                    </div>
                    <template #title><span>首页</span></template>
                </el-menu-item>
                <SubMenu :menus="appStore.menus" @context-call="contextMenuClick" />
            </el-menu>
        </div>
        <ContextMenu v-if="contextShow" :type="fileType" :position="position" @result="resultHandle"></ContextMenu>
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%">
            <el-form ref="contextForm" :model="dataForm">
                <el-form-item label="当前目录">
                    {{ dataForm.dir }}
                </el-form-item>
                <el-form-item label="英文名" prop="enName" :rules="[{ required: true, message: '请输入英文名', trigger: 'blur' }]">
                    <el-input v-model="dataForm.enName" clearable></el-input>
                </el-form-item>
                <el-form-item label="中文名" prop="chName" :rules="[{ required: true, message: '请输入中文名', trigger: 'blur' }]">
                    <el-input v-model="dataForm.chName" clearable></el-input>
                </el-form-item>
            </el-form>
            <div v-if="['page', 'entity'].includes(createType)">
                <el-form>
                    <el-form-item label='选择字段'>
                        <div class="flex-child-end">
                            <el-input style="width: 30%;" v-model="entityUrl"></el-input>
                            <el-button class="ml-10" type="primary" @click="getEntity()">请求</el-button>
                        </div>
                    </el-form-item>
                </el-form>
                <xkl-table max-height="300" :table="table" @selection-change="selectionChange">
                    <template #chName="{ row }">
                        <el-input v-model="row.chName"></el-input>
                    </template>
                    <template #span="{ row }">
                        <el-input-number :step="1" :min="1" :max="24" :precision="0" v-model="row.span"
                            placeholder="1 ~ 24"></el-input-number>
                    </template>
                    <template #type="{ row }">
                        <xkl-select v-model="row.type" :list="entypes"></xkl-select>
                    </template>
                    <template #_operation="{ row }">
                        <el-popover placement="bottom-start" trigger="hover">
                            <el-checkbox v-model="row.forForm">置入表单</el-checkbox>
                            <el-checkbox v-model="row.forTable">置入表格</el-checkbox>
                            <el-checkbox v-model="row.forQuery">置为搜索</el-checkbox>
                            <el-checkbox v-model="row.forRequired">置为必填</el-checkbox>
                            <template #reference>
                                <el-link type="primary" class="m-2">行为</el-link>
                            </template>
                        </el-popover>
                    </template>
                </xkl-table>
            </div>
            <template #footer>
                <el-button type="primary" @click="confirmForm">确定</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { Options } from 'vue-class-component'
import { BaseController } from '@xuekl/cli-base'
import LocalService from '@/service/local'
import { Local, LocalTable } from '@/entity/local'
import SubMenu from './SubMenu.vue'
import { nextTick } from 'vue'
import type { SideMenu, SelectItem } from '@xuekl/cli-base/type'
// import { widgetTypes } from '@/utils/source'
import useApp from '@/store/app'

@Options({
    components: {
        Document,
        Location,
        SubMenu
    },
    created() {
        // this.getWidgets()
        this.getMenus()
    },
    mounted() {
        document.addEventListener('click', () => {
            this.contextShow = false
        })
    }
})
export default class SideView extends BaseController {
    private localService = new LocalService()
    appStore = useApp()
    menus: SideMenu[] = []
    table: LocalTable = new LocalTable()
    isCollapse = false
    contextShow = false
    env = process.env.NODE_ENV
    entityUrl = ''
    entypes: SelectItem[] = []
    fileType = 'file' //file  folder
    baseFolder = {
        id: '101',
        fullPath: '/',
        title: '根目录',
        type: 'root'
    }
    position = {
        x: 100,
        y: 100
    }
    dialogVisible = false
    dialogTitle = ''
    createType = '' // 文件创建类型
    rootDir = ''
    dataForm = {
        id: '',
        dir: '',
        path: '',
        enName: '',
        chName: '',
        parent: ''
    }

    async getWidgets() {
        const data = await this.localService.getWidgets({})
        this.entypes = data
    }

    async getMenus() {
        // this.menus.length = 0
        // const data = await this.localService.getMenus({})
        // this.menus.push(...setFullPath(data))
        // this.appStore.initMenus()
    }

    contextMenuClick(item, e: MouseEvent) {
        if (this.env !== 'development') {
            return false
        }

        this.dataForm.id = item.id
        this.dataForm.dir = item.fullPath
        this.dataForm.path = item.path
        this.dataForm.chName = item.title
        this.dataForm.enName = item.name

        this.fileType = item.type
        this.contextShow = false
        nextTick(() => {
            // console.log(document.body.clientHeight);
            this.contextShow = true
            this.position.x = e.pageX;
            this.position.y = e.pageY;
            if (e.pageY > document.body.clientHeight - 240) {
                this.position.y = e.pageY - 240
            }
        })
    }

    resultHandle(val: { value: string, label: string }) {
        this.contextShow = false
        this.createType = val.value
        switch (this.createType) {
            case 'delete':
                this.fileRemove()
                break
            case 'rename':
                this.dialogVisible = true
                this.dialogTitle = val.label
                break
            case 'entity':
                this.dialogVisible = true
                this.dialogTitle = val.label
                break
            case 'dialogEdit':
            case 'subEidt':
                this.dialogVisible = true
                this.dialogTitle = val.label
                this.dataForm.parent = this.dataForm.enName
                this.dataForm.chName = ''
                this.dataForm.enName = this.createType === 'dialogEdit' ? 'DialogOperate' : 'PageOperate'
                break
            case 'dialogDetail':
            case 'subDetail':
                this.dialogVisible = true
                this.dialogTitle = val.label
                this.dataForm.parent = this.dataForm.enName
                this.dataForm.chName = ''
                this.dataForm.enName = 'PageInfo'
                break
            default:
                this.dialogVisible = true
                this.dialogTitle = val.label
                this.dataForm.chName = ''
                this.dataForm.enName = ''
                break
        }
    }
    fileRemove() {
        this.$messageBox.confirm(
            `将同步删除${this.dataForm.chName}代码文件，确定删除？`,
            '提示',
            {
                confirmButtonText: '确认',
                type: 'warning',
            }
        ).then(async () => {
            await this.localService.delete(this.dataForm)
            this.getMenus()
        }).catch(() => {
            this.$message.success('放下屠刀，立地成佛！')
        })
    }

    async doInsert() {
        const form = {
            ...this.dataForm,
            createType: this.createType,
            list: this.table.selectedData
        }
        await this.localService.insert(form)
        this.dialogVisible = false
        this.$message({
            message: '新增成功',
            type: 'success',
            onClose: () => {
                this.$messageBox.alert(
                    `操作菜单后需刷新页面`,
                    '提示',
                    {
                        confirmButtonText: '确认',
                        type: 'warning',
                    }
                ).then(async () => {
                    window.location.reload()
                })
            }
        })
    }

    async doInsertSub() {
        const form = {
            ...this.dataForm,
            createType: this.createType
        }
        await this.localService.insertSub(form)
        this.$message.success('新增成功')
        this.dialogVisible = false
    }

    async doRename() {
        await this.localService.rename(this.dataForm)
        this.getMenus()
        this.dialogVisible = false
        this.$message.success('操作成功')
        this.dialogVisible = false
    }

    async doGenEntity() {
        if (!this.table.selectedData.length) {
            this.$message.warning('请选择字段')
            return
        }
        for (let i = 0; i < this.table.selectedData.length; i++) {
            let item = this.table.selectedData[i]
            if (!item.chName) {
                this.$message.warning(`请输入${item.enName}的中文名`)
                return
            }
        }
        const form = {
            ...this.dataForm,
            list: this.table.selectedData
        }
        await this.localService.genEntity(form)
        this.dialogVisible = false
        this.$message.success('操作成功')
    }

    confirmForm() {
        // eslint-disable-next-line
        (this.$refs.contextForm as any).validate(async (valid: boolean) => {
            if (valid) {
                switch (this.createType) {
                    case 'rename':
                        await this.doRename()
                        break;
                    case 'entity':
                        await this.doGenEntity()
                        break;
                    case 'dialogEdit':
                    case 'subEidt':
                    case 'dialogDetail':
                    case 'subDetail':
                        await this.doInsertSub()
                        break;
                    default:
                        await this.doInsert()
                        break;
                }
            }
        })
    }

    async getEntity() {
        const data = await this.localService.getEntity(this.entityUrl)
        let pData = data
        if (Array.isArray(data)) {
            pData = data[0]
        }
        Object.keys(pData).forEach(key => {
            const local = new Local();
            local.enName = key
            local.value = pData[key]
            local.type = 'input'
            this.table.list.push(local)
        })

    }

    selectionChange(val: Local[]) {
        this.table.selectedData = val
    }

}
</script>
<style lang="scss">
.side-wrap {
    height: 100%;
    background-color: #25282c;
    display: flex;
    flex-direction: column;
    position: relative;
    z-index: 1001;

    .side-scroll {
        flex: 1;
        overflow-y: auto;
    }

    .title {
        font-size: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 220px;
        transition: .3s;
        // border-right: 1px solid #fff;
        color: #fff;
        height: 60px;

        .title-text {
            white-space: nowrap;
        }

        img {
            width: 40px;
        }

        &.callapse {
            width: 64px;
        }
    }

    .el-menu-item {
        margin: 0 10px;
        padding-left: calc(var(--el-menu-base-level-padding) + var(--el-menu-level) * var(--el-menu-level-padding) - 10px) !important;
    }

    .el-menu-item.is-active {
        border-radius: 4px;

        background-color: $primary--color;
    }
}
</style>